import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:xftpdemo/ise/utils/ise_sound_manage.dart';
import 'package:xftpdemo/ise/utils/xf_ise_manage.dart';
import 'package:xml2json/xml2json.dart';
import 'bean/ise_result_entity.dart';

/**
 * author：twopai
 * email：twopai@hotmail.com
 * des：基于讯飞测评webApi做的flutter版本
 * time：2022/02/16
 */
const host = 'ise-api.xfyun.cn';
const appId = 'f574a806';
const apiKey = 'b20276e51850ce7ced04cf8c32efe9de';
const apiSecret = 'MzEyODZhM2M4YWRmYWJjYjU3MDFmZmUz';

class IsePage extends StatefulWidget {
  const IsePage({Key key}) : super(key: key);

  @override
  _IsePageState createState() => _IsePageState();
}

class _IsePageState extends State<IsePage> {
  String _msg = '等待中...';
  XfIseManage _xf;
  //测评文本
  String checkTxt = '语音测评';

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    IseSoundRecord.init();
  }

  @override
  void dispose() {
    _xf?.close();
    IseSoundRecord.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: Text('语音测评'),
      ),
      body: Column(
        children: [
          RaisedButton(
            onPressed: () async {
              // MicRecord.startListening();
              await IseSoundRecord.startListening();
              setState(() {
                _msg = '录音中..';
              });
            },
            child: Text('开始录音'),
          ),
          RaisedButton(
            onPressed: connect,
            child: Text('停止录音'),
          ),
          Container(
            height: 20,
          ),
          Center(child: SingleChildScrollView(
            child: Text(_msg),
          )),
        ],
      ),
    );
  }

  connect() async {
    await IseSoundRecord.stopListening();
    setState(() {
      _msg = '录音停止,正在评估分值...';
    });
    XfIseManage.setCheckTxt(checkTxt: checkTxt);
    _xf = XfIseManage.connect(
      host,
      apiKey,
      apiSecret,
      appId,
      await IseSoundRecord.currentSamples(),
          (msg) {
        setState(() {
          String xmlStr=msg;
          final myTransformer = Xml2Json();
          myTransformer.parse(xmlStr);
          String _msg2 = myTransformer.toGData();
          Map<String, dynamic> _map = json.decode(_msg2);
          IseResultEntity iseResultEntity = IseResultEntity.fromJson(_map);
          var xmlResult = iseResultEntity.xmlResult;
          var readSentence = xmlResult.readSentence;
          var recPaper = readSentence.recPaper;
          var result = recPaper.readSentence;
          _msg='''
                  篇章开始: ${result.begPos}, 
                  篇章结束: ${result.endPos}。
                  篇章内容: ${result.content}。
                  总分: ${result.totalScore}。
                  准确度评分: ${result.accuracyScore}。
                  流畅度评分: ${result.fluencyScore}。
                  完整度评分: ${result.integrityScore}。
                  是否乱读: ${result.isRejected}。
                ''';
          print('myTransformer-->_map=$_msg2');
        });
      },
    );
  }
}


